/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.web;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.boxin.ims.modules.wechat.entity.MassMedia;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.service.MassMediaService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.utils.TokenUtils;
import com.boxin.ims.modules.wechat.utils.WechatInterfaceUtils;
import com.boxin.ims.modules.wechat.utils.WechatMenuUtils;
import com.boxin.ims.modules.wechat.utils.WechatUtils;

/**
 * 群发素材管理Controller
 * @author XiaoQian
 * @version 2014-03-28
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/wechat/massMedia")
public class MassMediaController extends BaseController {

	@Autowired
	private MassMediaService massMediaService;
	
	@Autowired
	private WeChatService weChatService;
	
	@Autowired
	WechatDaoHelper wechatDaoHelper;
	
	@Autowired
	private WechatMemberService wechatMemberService;
	
	private final Logger logger = Logger
			.getLogger(MassMediaController.class);
	
	@ModelAttribute
	public MassMedia get(@RequestParam(required=false) Long id) {
		if (id != null){
			return massMediaService.get(id);
		}else{
			return new MassMedia();
		}
	}
	
	@RequiresPermissions("wechat:massMedia:view")
	@RequestMapping(value = {"list", ""})
	public String list(MassMedia massMedia, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			massMedia.setUser(user);
		}
        Page<MassMedia> page = massMediaService.find(new Page<MassMedia>(request, response), massMedia); 
        model.addAttribute("page", page);
		return "modules/wechat/massMediaList";
	}

	@RequiresPermissions("wechat:massMedia:view")
	@RequestMapping(value = "form")
	public String form(MassMedia massMedia, Model model) {
	
		User user = UserUtils.getUser();
		if (massMedia.getUser() == null || massMedia.getUser().getId() <1){
			massMedia.setUser(user);
		}
		
		model.addAttribute("massMedia", massMedia);
		return "modules/wechat/massMediaForm";
	}

	@RequiresPermissions("wechat:massMedia:edit")
	@RequestMapping(value = "save")
	public String save(@RequestParam("file") MultipartFile image,MassMedia massMedia, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) {
		String msgtype=request.getParameter("msgtype");
		massMedia.setMsgtype(msgtype);
		massMedia.setUpdateTime(new Date());
		if (!beanValidator(model, massMedia)){
			return form(massMedia, model);
		}
		
		if(image != null && image.getOriginalFilename().length()>4){
			String massMediaPath = WechatUtils.getWechatMassMediaResourceSavePath(request)+File.separator;
			FileUtils.createDirectory(massMediaPath);
			String sname = image.getOriginalFilename();
			String fileType = sname.substring(sname.lastIndexOf("."));
			String fname  = UserUtils.getUser().getLoginName()+	"_massMedia_"+System.currentTimeMillis()+fileType;
			File file = new File(massMediaPath+fname);
			System.out.println("保存文件:"+massMediaPath+fname);
			try {
				image.transferTo(file);
				massMedia.setPicurl("http://weixin.zhaotang.net/zt/userfiles/massmedia/"+file.getName());
			} catch (Exception e) {
				System.out.println("上传文件失败:"+massMediaPath+fname);
				e.printStackTrace();
			}
		}
		
		massMediaService.save(massMedia);
		addMessage(redirectAttributes, "保存群发素材管理成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/massMedia/?repage";
	}
	
	@RequiresPermissions("wechat:massMedia:edit")
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		massMediaService.delete(id);
		addMessage(redirectAttributes, "删除群发素材管理成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/massMedia/?repage";
	}
	
	@RequiresPermissions("wechat:massMedia:edit")
	@RequestMapping(value = "sendNews")
	public String sendNews(final Long id, final RedirectAttributes redirectAttributes,HttpServletRequest request) {
		
		
		final String massType=request.getParameter("massType");
		System.out.println(massType);
		Runnable runner = new Runnable() {
			@Override
			public void run() {
				MassMedia massMedia=massMediaService.get(id);
				try {
					User user=UserUtils.getUser();
					if(user.getInterfaceFlag()==true){
						
						WeChat weChat= weChatService.getWeChatByUserId(user.getId());
						String accessToken=TokenUtils.getAPIToken(weChat) ;
						
						Map<String, Object> memberParams=new HashMap<String, Object>();
						
						memberParams.put("user_id", user.getId());
						List<Map<String, Object>>  list=new ArrayList<Map<String, Object>>();
						if(massType.equals("1")){
							
							list=wechatDaoHelper.selectMemberByDay(memberParams);
						}else if(massType.equals("0")){
							list=wechatDaoHelper.selectSignUPMemberByDay(memberParams);
						}else if(massType.equals("2")){
							list=wechatDaoHelper.selectPlatformByDay(memberParams);
						}
						System.out.println(list.size());
						
						for (int i = 0; i < list.size(); i++) {
							String params=WechatInterfaceUtils.newsMessageParams(list.get(i).get("wechat_id").toString(), massMedia.getTitle(), massMedia.getDescription(), massMedia.getUrl(), massMedia.getPicurl());
							String str=WechatInterfaceUtils.sendServiceMessage(params, accessToken);
							if(massType.equals("2")){
								logger.debug("群发--发送信息返回的状态码"+str);
							}else{
								logger.debug("群发--当前发送的会员手机为" + list.get(i).get("mobile")+"发送信息返回的状态码"+str);
							}
						}
						
						addMessage(redirectAttributes, "群发成功");
					}else{
						addMessage(redirectAttributes, "您没有开通高级接口");
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
					}
				};
				new Thread(runner).start();
				
		return "redirect:"+Global.ADMIN_PATH+"/wechat/massMedia/?repage";
	}
	
	
	
//	@RequiresPermissions("wechat:massMedia:edit")
//	@RequestMapping(value = "sendNews")
//	public String sendNews(Long id,RedirectAttributes redirectAttributes) {
//				MassMedia massMedia=massMediaService.get(id);
//				try {
//					User user=UserUtils.getUser();
//					if(user.getInterfaceFlag()==true){
//						
//						WeChat weChat= weChatService.getWeChatByUserId(user.getId());
//						String accessToken=WechatMenuUtils.getAccessToken(weChat.getAppId(), weChat.getAppSecret());
//						
//						List<WechatMember>  list=wechatMemberService.findAllMembersByUserId(user.getId());
//						
//						for (int i = 0; i < list.size(); i++) {
//							String params=WechatInterfaceUtils.newsMessageParams(list.get(i).getWechatId(), massMedia.getTitle(), massMedia.getDescription(), massMedia.getUrl(), massMedia.getPicurl());
//							
//							WechatInterfaceUtils.sendServiceMessage(params, accessToken);
//						}
//						
//						addMessage(redirectAttributes, "群发成功");
//					}else{
//						addMessage(redirectAttributes, "您没有开通高级接口");
//					}
//					
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				
//		return "redirect:"+Global.ADMIN_PATH+"/wechat/massMedia/?repage";
//	}
	
	
	@RequiresPermissions("wechat:massMedia:edit")
	@RequestMapping(value = "sendNewsByWechatId")
	public String sendNewsByWechatId( RedirectAttributes redirectAttributes,HttpServletRequest request) {
		User user=UserUtils.getUser();
		String id=request.getParameter("id");
		
		WechatMember wechatMember=wechatMemberService.get(Long.parseLong(id));
		String massMedia_id=request.getParameter("massMedia_id");
		MassMedia massMedia=massMediaService.get(Long.parseLong(massMedia_id));
		try {
			
			if(user.getInterfaceFlag()==true){
				
				WeChat weChat= weChatService.getWeChatByUserId(user.getId());
				String accessToken=TokenUtils.getAPIToken(weChat);
				
				String params=WechatInterfaceUtils.newsMessageParams(wechatMember.getWechatId(), massMedia.getTitle(), massMedia.getDescription(), massMedia.getUrl(), massMedia.getPicurl());
				
				WechatInterfaceUtils.sendServiceMessage(params, accessToken);
				addMessage(redirectAttributes, "发送成功");
			}else{
				addMessage(redirectAttributes, "您没有开通高级接口");
			}
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "redirect:"+Global.ADMIN_PATH+"/wechat/massMedia/?repage";
	}
	
	
	@RequiresPermissions("wechat:massMedia:view")
	@RequestMapping(value = "sendNewsform")
	public String sendNewsform(Long id, RedirectAttributes redirectAttributes, Model model) {
		model.addAttribute("id", id);
		
		User user=UserUtils.getUser();
		List<MassMedia> list=massMediaService.findByUserId(user.getId());
		
		model.addAttribute("list", list);
		return "modules/wechat/sendNewsForm";
	}
	
	
	
	@RequiresPermissions("wechat:massMedia:view")
	@RequestMapping(value = "sendNewsConfig")
	public String sendNewsConfig(Long id, RedirectAttributes redirectAttributes, Model model) {
		
		model.addAttribute("id", id);
		return "modules/wechat/sendNewsConfig";
	}
	

}
